<!-- 批量上传图片插件:: -->
<!--
    <myUpload
        style="display:inline-block;"// 支持自定义行块和样式
        temp='initTemp' // 先缓存 最后dad.initTemp(callback) => 才统一上传 所有接口都访问过后 执行 callback(data)
        readonly // 开启只读模式 不可修改和删除 只能预览
        multiple //支持一次性多选图片
        limit='3' // 限制最多上传的图片组数量
        url="https://upload-test.mfjyun.com/upload/uploadfile" //要上传的服务器地址
        :data="{files: '$file$', catalog: 'mflj', appkeyid: 'mofanglj', appkeyvalue: 'mofanglj2018'}" //上传时的必要参数 其中 $file$的key名称"files"是上传文件的变量
        myModel="myPic"> // 上传后的图片数组 => 默认携带有 { pictureUrl:url,id:'myImage'+Date.now(),isLoading: false } (也可以设置初始化图片 dad.myPic = [{pictureUrl:'pictureUrl'},'pictureUrl'])
    </myUpload>
-->
<template>
<div style="white-space: nowrap;overflow: auto;padding-top: 10px;">
    <div v-if="dialogVisible">
        <el-dialog
            id="myPreview"
            width="70%"
            top="13vh"
            :modal-append-to-body=false
            :visible="true"
            :before-close="closePreview"
            >
            <img width="100%" :src="dialogImageUrl" alt="貌似图片加载失败了...">
        </el-dialog>
    </div>
    <div
        style="width:220px;display:inline-block;position:relative;float:left;"
        :style=' readonly===undefined ? "cursor: pointer;" : "" '
        v-for="(image,index) in imageList"
        :key="index">
        <div
            style="width: 190px;height: 170px;margin: 0 auto;margin-bottom: 10px;border-radius:4px;color:#8c939d;border: 1px solid #A8A8A8;border-style:dashed;"
            :style="isLoading===null?'background-color: rgba(0,0,0,0.5);color:white;':'background:#fdfdfd'"
            id="myUpload"
            @click="readonly===undefined && prevUpload(image,index)"
            >
            <div vif="image.pictureUrl" style="width: 100%;height: 100%;position: relative;">
                <img :src="image.pictureUrl" style="width:100%;height:100%;">
                <div v-if='image.isLoading' style="z-index:77;position: absolute;left: 0;top: 0;width: 100%;height: 100%;background-color: rgba(0,0,0,0.5);" >
                    <i class="el-icon-loading" style="font-size: 30px;position: absolute;width: 30px; height: 30px; left: 50%; margin-left: -15px; top: 50%; margin-top: -15px; color: white;" ></i>
                </div>
                <div id="myPreview" class="" style="width: 100%;
                    height: 100%;
                    display: none;
                    font-size: 22px;
                    color: white;
                    letter-spacing: 0.3em;
                    line-height: 170px;
                    position: absolute;
                    z-index: 7777 !important;
                    left: 0;
                    top: 0;
                    text-align: center;">
                    <span class="el-icon-zoom-in" style="cursor:pointer;" id="myPreviewIcon" @click.stop="dialogImageUrl=image.pictureUrl,dialogVisible=true"></span>
                    <span v-if="readonly===undefined" class="el-icon-delete" style="cursor:pointer;" id="myPreviewIcon" @click.stop="imageList.splice(index,1)"></span>
                </div>
                <i v-if="readonly===undefined" class="el-icon-close" id='deletePic' @click.stop="imageList.splice(index,1)"></i>
                <!-- <el-button v-if="!readonly" type="primary" size="mini" style="position: absolute;left: 0;bottom: -36px;" :style="firstPic!==false?'':'left:55px;'" class="el-icon-upload"> 上传</el-button> -->
                <!-- <br>
                <span v-if="firstPic!==false" style="display: block;text-align: center;margin-top: 6px;">
                    <el-button v-if="!readonly" :type="image.firstState==='1'?'warning':'success'" size="mini" style="aposition: absolute;right: 0;bottom: -36px;" :class="image.firstState==='1'?'el-icon-error':'el-icon-success'" @click.stop="setFirstPic(switch,image)"> {{ image.firstState==='1'?(!readonly?'取消首图':'我的首图'):(!readonly?'设置首图':'') }}</el-button>
                    <el-button v-else-if="image.firstState==='1'" type="warning" size="mini" style="aposition: absolute;right: 0;bottom: -36px;left: 50%;amargin-left: -48px;" class="el-icon-success" :disabled=true> 我的首图</el-button>
                </span> -->
            </div>
            <!-- <i v-else :class="el-icon-question" style="font-size: 30px;width:190px;height:170px;line-height:170px;text-align: center;" :style="readonly?'':'cursor:pointer;'"></i> -->
        </div>
    </div>

    <div
        class=""
        style="width:220px;display:inline-block;position: relative;"
        v-if="!limit ? readonly===undefined || !imageList.length : readonly===undefined && imageList.length<limit"
        >
        <!-- <div v-if="dialogImageUrl" style="width: 190px;height: 170px;margin: 0 auto;margin-bottom: 10px;border-radius:4px;color:#8c939d;border: 1px solid #A8A8A8;" id="myUpload" @click="console($refs.upload)">
            <img :src="dialogImageUrl" alt="" style="width:100%;height:100%;">
        </div> -->
        <div
            style="width: 190px;height: 170px;margin: 0 auto;margin-bottom: 10px;border-radius:4px;color:#8c939d;border: 1px solid #A8A8A8;border-style:dashed;"
            :style="isLoading?'background-color: rgba(0,0,0,0.5);color:white;':'background:#fdfdfd'"
            id="myUpload"
            @click="prevUpload('')"
            >
            <!-- <img v-if="dialogImageUrl" :src="dialogImageUrl" alt="" style="width:100%;height:100%;"> -->
            <i :class="readonly?'el-icon-question':isLoading?'el-icon-loading':'el-icon-plus'" style="font-size: 30px;width:190px;height:170px;line-height:170px;text-align: center;" :style="readonly?'':'cursor:pointer;'"></i>
        </div>
        <!-- <el-button type="primary" size="mini">上传</el-button> -->
        <!-- <el-button type="primary" size="mini" style="position: absolute;right: -73px;top: 50px;" @click="prevUpload" class="el-icon-upload"> 上传</el-button>
        <br>
        <el-button type="danger" size="mini" style="position: absolute;right: -73px;top: 100px;" class="el-icon-delete" @click="imageList=null"> 删除</el-button> -->
    </div>

    <el-upload
        style="display:inline-block;display:none;"
        :action="url||''"
        :show-file-list="false"
        drag
        :multiple='multiple!==undefined'
        :limit="0"
        id="__upload__2"
        ref="upload"
        accept="image/jpeg,image/png"
        :auto-upload="true"
        :http-request="myRequest"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        >
        <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
        <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

    <el-upload
        style="display:inline-block;display:none;"
        :action="url||''"
        :show-file-list="false"
        drag
        :multiple='false'
        :limit="0"
        id="__upload__"
        ref="upload"
        accept="image/jpeg,image/png"
        :auto-upload="true"
        :http-request="myRequest"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        >
        <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
        <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

</div>
</template>
<script>
    // import myhttp from '@/api/myhttp.js'

    // 利用 new FormData进行批量上传文件
    /* var PostFile = function(url,formData,then){
        jQuery.ajax({
            url: url,
            type: 'post',
            data: formData, //new FormData(form),
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(res){
                typeof then === 'function' && then(res);
            },
            error: function(res){
                typeof then === 'function' && then(res,true);
            }
        });
    }; */
    var dad, myModel, multiple, limit;
    export default {
        ref: false,
        global: false,
        name: 'myUpload',
        data () {
            return {
                dialogVisible: false,
                dialogImageUrl: '',
                isLoading: false,
                imageList: [],
            }
        },
        props: ['url','data','temp','multiple','limit','readonly','myModel','dad','son','dadSon'],
        methods: {
            closePreview(done) {
                this.dialogVisible = false;
            },

            /*setFirstPic(switch,image) {
                var temp =  this.tempLast || image;
                // console.error(image,this.tempLast);
                image.firstState = image.firstState==='1' ? '0' : '1';
                temp.id!==image.id && (temp.firstState='0');
                this.tempLast = image;
            },*/

            prevUpload(image) {
                this.tempImage = image;
                var click = this.click;
                if(click && click()===false) return;
                var el = document.querySelector( image ? 'div#__upload__ div.el-upload-dragger' : 'div#__upload__2 div.el-upload-dragger' );
                el && el.click();
            },
            myRequest(param,obj,index) {
                const imageList = this.imageList;
                if ( multiple && limit ) {
                    if( imageList.length >= limit ) return;
                };
                if(!obj) {
                    var fileObj = param.file;
                    var last = this.tempImage;
                    // console.log(param,b); //return;
                    // this.imageUrl = URL.createObjectURL(fileObj);
                    if( this.temp !== undefined ) {
                        if(!last){
                            imageList.push({
                                pictureUrl: URL.createObjectURL(fileObj),
                                $file$: fileObj,
                                isLoading: false,
                                id: 'myImage' + Date.now()
                            });
                        }else {
                            last.pictureUrl = URL.createObjectURL(fileObj);
                            last.$file$ = fileObj;
                        };
                        setTimeout( ()=>(last||this)['isLoading'] = false, 50 );
                        // console.error(imageList);
                        return;
                    };
                }else {
                    var fileObj = obj.$file$;
                    if(!fileObj) return obj && $return.sleep(0,index);
                    var last = obj;
                };
                (last||this)['isLoading'] = true;
                // FormData 对象
                var form = new FormData();
                // console.error(fileObj);
                // 文件对象
                // form.append("files", fileObj);
                // form.append('catalog', 'mflj');
                // form.append('appkeyid', 'mofanglj');
                // form.append('appkeyvalue', 'mofanglj2018');
                var data = this.data;
                if(data) {
                    forObj(data,(v,key)=>{
                        form.append( key,
                            v==='$file$' ? fileObj : v === '$fileName$' ? fileObj.name : v
                        );
                    });
                };
                $.file($.api.uploadPic,form,(res,err)=>{
                    // console.log(res,err);
                    if( res.result !== 'success' || err ) {
                        setTimeout( ()=>(last||this)['isLoading'] = false, 100 );
                        !obj ? msgError(this,res.message||'上传图片失败！') : $return(index,res);
                    }else{
                        obj && delete obj.$file$;
                        setTimeout(
                            ()=>{
                                (last||this)['isLoading'] = false;
                                const real = res.$real$ = 'http://47.104.23.200:8014/yz_file/picture/' + res.items.replace('header/','');
                                last
                                ? last.pictureUrl = real
                                : imageList.push({
                                    pictureUrl: real,
                                    isLoading: false,
                                    id: 'myImage' + Date.now()
                                });
                                obj && $return(index,res);
                            },
                            200
                        );
                        // console.error(this.imageList);
                    };

                });
                /*myhttp.postFile(param.action,form).then(res => {
                    if(res.data.success === true){
                        setTimeout(
                            ()=>{
                                (last||this)['isLoading'] = false;
                                res = res.data.data;
                                last
                                ? last.pictureUrl = res
                                : this.imageList.push({
                                    pictureUrl: res,
                                    isLoading: false,
                                    id: 'myImage' + Date.now()
                                });
                            },
                            200
                        );
                        // console.error(this.imageList);
                    } else {
                        setTimeout( ()=>(last||this)['isLoading'] = false, 100 );
                        msgError(this,res.data.message||'上传图片失败！');
                    };
                });*/
            },
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                // console.log(res, file);
            },
            beforeAvatarUpload(file) {
                // console.log(777777777,file);
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 20;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                };
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 20MB!');
                };
                return isJPG && isLt2M;
            },
        },
        created() {
            dad = this.parseDadSon('myUpload');
            multiple = this.multiple !== undefined;
            limit = Number(this.limit);

            myModel = this.myModel;
            if( myModel ) {
                const last = dad[myModel];
                var imageList = this.imageList;
                Array.isArray(last) && ( this.init0 = true, imageList = this.imageList = last.map(v=>{
                    const type = typeOf(v);
                    if( type === 'object' ) v.isLoading = false, !v.hasOwnProperty(id) && ( v.id = randomStr('myImage',13) )
                    else v = { pictureUrl: type==='string' ? v : '', isLoading: false, id: randomStr('myImage',13) }
                    return v;
                }) );
                dad.myBind( myModel,img=>{
                    // console.error( JSON.stringify(img) );
                    if(this.init) { delete this.init; return; };
                    this.imageList = img.map(v=>{
                        typeof v === 'string' && ( v = {pictureUrl:v} );
                        v.id = 'myImage' + Date.now();
                        v.isLoading = false;
                        return v;
                    });
                },imageList );
                // console.error(this,dad[myModel],myModel);
                // this.init = true;
                // dad[myModel] = this.imageList;
            };

            const temp = this.temp;
            if(temp) {
                dad[temp] = (callback)=>{
                    // return console.warn(this.imageList);
                    const map = mapArr( this.imageList, (obj,index)=>obj.$file$ && this.myRequest.waitRun(null,obj,index) );
                    map.length > 0
                    ? map.all(data=>{
                        // console.error(data);
                        callback.call(this,data);
                    })
                    : setTimeout(()=>callback.call(this,[]),0);
                };
            };
        },
        watch: {
            imageList(list) {
                if(this.init0) return delete this.init0;
                if(myModel) {
                    // console.error(list,dad);
                    this.init = true;
                    dad[myModel] = this.imageList;
                };
            }
        },

        mounted() {
            // console.error(this.readonly,)
        },
        destroyed() {

        }
    }
</script>
<style scoped>
    #myPreview {
        z-index:77777777 !important;
        transition: 1.0s;
        background-color: rgba(0, 0, 0, 0.5);
    }
    #myPreview+.v-modal {
        z-index: 777777 !important;
    }
    #myUpload:hover #myPreview, #myUpload:hover +#myPreview{
        display: block !important;
    }
    #myPreview:hover {
        display: block;
    }

    #myPreviewIcon:hover {
        text-shadow: 1px 1px #999;
    }

    #deletePic {
        position: absolute;
        color: white;
        right: -8px; top: -8px;
        font-size: 14px;
        z-index: 77777;
        border: 1px solid red;
        background: red;
        border-radius: 50%;
        padding: 2px;
    }
    #deletePic:hover {
        background: #ec0f0f !important;
        color: #fbfbfb !important;
    }

</style>
